<template>
	<view class="content">
		<view class="uni-panel-c">
			<view class="uni-panel-top">
				<text class="uni-text-logo">连连看测试</text>
				<text class="uni-text-count">先消除不认识的单词后再点击灯泡按钮</text>
			</view>
			<view class="uni-panel-bottom">
				<view class="uni-panel-item">
					<image class="uni-image" src="/static/img/back.png" mode="widthFix" @click="clickBack"></image>
					<view class="uni-panel-item-info">
						<text class="uni-text-item">已检测单词：</text>
						<text class="uni-text-item">{{curIndex}}</text>
					</view>
					<view class="uni-panel-item-info">
						<text class="uni-text-item">单词总数：</text>
						<text class="uni-text-item">{{allWords.length}}</text>
					</view>
					<view class="uni-panel-item-info">
						<image class="uni-image-box" src="/static/img/lamp.png" mode="widthFix" v-if="isShowLammp" @click="clickLamp"/>
					</view>
					<view class="uni-panel-item-info">
						<image class="uni-image-box" src="/static/img/gold.png" mode="widthFix" />
						<text class="uni-text-item">{{goldNum}}</text>
					</view>
				</view>
				<view class="uni-panel-english">
					<view class="uni-word-item" v-for="(item, index) in englishWords" :key="index" 
					@click="clickEnglishWord(item)" 
					:style="{opacity: item.word?1:0}"
					:animation="item.animationData" 
					@transitionend="animationEnd(item)"
					:id="'english_'+index">
						<view class="uni-panel-noimage" />
						<view class="uni-text-word" :style="{'background-color': item.clicked?'steelblue':'white'}">{{item.word}}</view>
					</view>
				</view>
				<view class="uni-panel-english">
					<view class="uni-word-item" v-for="(item, index) in chineseWords" :key="index" 
					@click="clickChineseWord(item)" 
					:style="{opacity: item.word?1:0}"
					:animation="item.animationData"
					@transitionend="animationEndChinese(item)"
					:id="'chinese_'+index">
						<image class="uni-image-word" :src="'/static/img/word_zh'+index+'.png'" mode="widthFix" />
						<view class="uni-text-word" :style="{'background-color': item.clicked?'steelblue':'white'}">{{item.word_zh}}</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getWordInfo, playMusic, addGold, editNewWord } from '@/api/api.js';
	import store from "../../store";
	import { HTTP_REQUEST_URL, VOICE_PATH, LIMIT } from '@/config/app.js';
	export default {
		mounted() {
		        // #ifdef APP-PLUS
		        plus.screen.lockOrientation('landscape');
		        // #endif
		    },
		data() {
			return {
				userId: 0,
				accountName: '',
				curIndex: 0,
				allWords: [],
				englishWords: [],
				chineseWords: [],
				isPlayMusic: false,
				isShowLammp: true,
				goldNum: 0
			}
		},
		onLoad(options) {
			let words = []
			if( options.words){
				let temp = decodeURIComponent(options.words)
				words = temp.split(',')
			}
			if( options.book_id){
				this.book_id = parseInt(options.book_id);
			}
			const userInfo = store.state.app.userInfo;
			if( userInfo){
				this.accountName = userInfo.nickname;
				this.userId = userInfo.id;
				this.goldNum = userInfo.balance;
			}
			let student = uni.getStorageSync('student_info');
			if( student){
				this.accountName = student.nickname;
				this.userId = student.id;
				this.goldNum = student.balance;
			}
				
			let that = this;
			let params = {words, book_id: this.book_id};
			getWordInfo(params).then(res => {
				console.log(res)
				if( res.data ){	
					this.allWords = res.data;
					this.allWords.sort(() => Math.random() - 0.5);
					this.pageCount = Math.floor(this.allWords.length/LIMIT);
					if(this.pageCount*LIMIT < this.allWords.length){
						this.pageCount++;
					}
					this.showPage = 0;
					that.refreshWord();
				}					
			})
		},
		methods: {
			clickBack(){
				uni.navigateBack();
			},
			refreshWord(){
				this.isShowLammp = true;
				this.indexShow = 0;
				let showIndex = this.showPage * LIMIT;
				this.englishWords = [];
				this.chineseWords = [];
				for( let i=0; i<LIMIT; i++){
					if( showIndex >= this.allWords.length){
						break;
					}
					let item = this.allWords[showIndex];
					this.englishWords.push({word: item.word, clicked:false, word_zh: item.word_zh})
					this.chineseWords.push({word: item.word, clicked:false, word_zh: '？？？'})
					showIndex++;
				}
				this.chineseWords.sort(() => Math.random() - 0.5);
			},
			clickLamp(){
				this.isShowLammp = false;
				let handleItems = [];
				for( let itemEnglish of this.englishWords){
					if( '' == itemEnglish.word){
						continue;
					}
					let itemChinese = this.chineseWords.find( i=> {
						return handleItems.indexOf(i)<0 && i.word==itemEnglish.word;
					});
					if( itemChinese){
						handleItems.push( itemChinese);
						itemChinese.word_zh = itemEnglish.word_zh;
					}else{
						itemChinese = this.chineseWords.find( i=> {
							return handleItems.indexOf(i)<0 && i.word!='';
						});
						if( itemChinese){
							handleItems.push( itemChinese);
							itemChinese.word = itemEnglish.word;
							itemChinese.word_zh = itemEnglish.word_zh;
						}
					}
				}
			},
			innerClickWord( item, selfWords, otherWords){
				for(let i of selfWords){
					i.clicked = false;
				}
				let chineseItem = otherWords.find( i=>{ return i.clicked});
				if(chineseItem){
					chineseItem.clicked = false;
					if(this.isShowLammp){
						// 加入到生词本
						let params = {user_id: this.userId,
										book_id: this.book_id,
										word: selfWords==this.englishWords?item.word:chineseItem.word,
										is_add: true};
						editNewWord(params).then(res => {
							console.log(res)
						})
						playMusic('/static/error.mp3');
						chineseItem.word = '';
						item.animationData = {}
						this.animationEnd(item)
					}else{
						let that = this;
						let addGoldNum = 1;
						if(this.isShowLammp || chineseItem.word == item.word){
							playMusic('/static/gold.mp3');
							const query = uni.createSelectorQuery().in(this);
							query.selectAll('.uni-word-item').boundingClientRect(data => {
								// 开始动画
								if( selfWords == this.englishWords){
									that.beginAnimation(item, chineseItem, data);
								}else{
									that.beginAnimation(chineseItem, item, data);
								}
							}).exec();
						}else{
							addGoldNum = -1;
							playMusic('/static/error.mp3');
							uni.showToast({
								title: '好像不对哦',
								icon: 'error',
								duration: 2000
							});
						}
						let params = {id: this.userId, addGoldNum};
						addGold(params).then(res => {
							if( 0 == res.code){
								this.goldNum += addGoldNum;
								store.commit('changInfo', {
									amount1:'balance', 
									amount2:this.goldNum,
								});
							}
						})
					}
					return;
				}
				item.clicked = true;
			},
			clickEnglishWord(item) {
				if(!item.word){
					return;
				}
				this.playWord( item.word)
				
				this.innerClickWord( item, this.englishWords, this.chineseWords);
			},
			clickChineseWord(item) {
				if(!item.word){
					return;
				}
				this.innerClickWord( item, this.chineseWords, this.englishWords);
			},
			playWord(word) {
				if(this.isPlayMusic){
					return;
				}
				let filename = HTTP_REQUEST_URL + VOICE_PATH + word + '.mp3'
				let that = this;
				playMusic( filename, playing=>{
					that.isPlayMusic = playing;
				})
			},
			animationEnd(item){
				if(item.animationData){
					//console.log(item)
					item.word = ''
					item.animationData = undefined;
					
					this.indexShow += 1;
					this.curIndex += 1;
					if(this.indexShow >= LIMIT){
						this.showPage += 1;
						let that = this;
						setTimeout(() => {
							if( this.showPage >= this.pageCount){
								uni.navigateBack();
							}else{
								that.refreshWord();
							}
						}, 500)
					}
				}
			},
			animationEndChinese(item){
				if(item.animationData){
					item.word = ''
					item.animationData = undefined;
				}
			},
			beginAnimation(englishItem, chineseItem, dataView){
				let englishIndex = this.englishWords.indexOf(englishItem);
				let chineseIndex = this.chineseWords.indexOf(chineseItem);
				if( englishIndex >= 0 && chineseIndex >= 0){
					let englishId = 'english_' + englishIndex;
					let chineseId = 'chinese_' + chineseIndex;
					let englishPos = dataView.find( item=>{return item.id==englishId});
					let chinesePos = dataView.find( item=>{return item.id==chineseId});
					if( englishPos && chinesePos){
						let midLeft = (englishPos.left + chinesePos.left)/2;
						let midTop = (englishPos.top + chinesePos.top)/2;
						const engAnimation = uni.createAnimation();
						engAnimation.translate(midLeft-englishPos.left, midTop-englishPos.top).step({duration:200});
						//engAnimation.opacity( 0).step({duration:1})
						engAnimation.translate( 0, 0).step({duration:1})
						englishItem.animationData = engAnimation.export();
						
						const chiAnimation = uni.createAnimation();
						chiAnimation.translate(midLeft-chinesePos.left, midTop-chinesePos.top).step({duration:200})
						//chiAnimation.opacity( 0).step({duration:1})
						chiAnimation.translate( 0, 0).step({duration:1})
						chineseItem.animationData = chiAnimation.export();
					}
				}
			},
		}
	}
</script>

<style>
	page {
		height: 100%;
	}
	.content {
		width: 100%;
		height: 100%;
		background-image: url('../../static/img/bg.jpg');
		background-size: 100% 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.uni-panel-c {
		width: 90%;
		height: 100%;
		display: flex;
		flex-direction: column;
	}
	
	.uni-panel-top {
		width: 100%;
		height: 20%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.uni-image {
		width: 6%;
	}
	.uni-text-logo{
		color: white;
		font-size: 5vmin;
		text-align: center;
		font-weight: bold;
		letter-spacing: 2rpx;
	}
	.uni-text-count{
		color: white;
		font-size: 4vmin;
		text-align: center;
	}
	
	.uni-panel-bottom-bk {
		position: absolute;
		left: 5%;
		top: 20%;
		width: 90%;
		height: 80%;
		background-color: white;
		opacity: 0.5;
		border-radius: 40rpx;
	}
	.uni-panel-bottom {
		width: 100%;
		height: 80%;
		display: flex;
		flex-direction: column;
		align-items: center;
		z-index: 1;
	}
	.uni-panel-item {
		background-color: #f5f7e2;
		width: 100%;
		height: 10%;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		border-radius: 20rpx;
	}
	.uni-panel-item-info {
		width: 20%;
		height: 90%;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
	.uni-text-item{
		font-size: 4vmin;
		color: royalblue;
		letter-spacing: 2rpx;
		margin: 0 2% 0 2%;
		display: flex;
		align-items: center;
	}
	.uni-panel-box{
		width: 10%;
		display: flex;
		flex-direction: row;
	}
	.uni-image-box{
		width: 25%;
	}
	
	.uni-panel-english {
		width:100%;
		height:45%;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
	
	.uni-word-item {
		height: 60%;
		width: 17%;
		margin-left: 2%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.uni-panel-noimage{
		width: 40%;
		height: 20%;
	}
	.uni-image-word{
		width: 40%;
		height: 50%;
	}
	
	.uni-text-word{
		width: 100%;
		height: 50%;
		font-size: 3vmin;
		color: black;
		font-weight: bold;
		border-radius: 20rpx;
		box-shadow: 6px 6px 2px 1px rgba(0, 0, 0, .2);
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>
